<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="空间编码" prop="lcCode">
        <el-input
          v-model="queryParams.lcCode"
          placeholder="请输入空间编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="空间名称" prop="lcName">
        <el-input
          v-model="queryParams.lcName"
          placeholder="请输入空间名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="空间状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择空间状态" clearable>
          <el-option
            v-for="dict in dict.type.pj_location_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-row>
        <el-form-item label="设备编号" prop="deviceNo">
          <el-input
            v-model="queryParams.deviceNo"
            placeholder="设备编号"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 100px"
          />
        </el-form-item>
        <el-form-item label="通道号" prop="channelNo">
          <el-input
            v-model="queryParams.channelNo"
            placeholder="通道号"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 100px"
          />
        </el-form-item>
        <el-form-item label="起止米标" prop="startMeter">
          <el-input-number
            v-model="queryParams.startMeter"
            placeholder="起始"
            :precision="0"
            :step="1"
            clearable
            style="width: 110px"
          />
        </el-form-item>
        <el-form-item label="-" prop="endMeter" label-width="10">
          <el-input-number
            v-model="queryParams.endMeter"
            placeholder="结束"
            :precision="0"
            :step="1"
            clearable
            style="width: 110px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:location:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleImport"
          v-hasPermi="['project:location:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="locationList"
      row-key="lcId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <!--      <el-table-column label="空间父亲id" prop="lcPid" />-->
      <el-table-column label="空间编码" align="left" prop="lcCode" width="300"/>
      <el-table-column label="空间名称" align="left" prop="lcName" width="300" />
<!--      <el-table-column label="空间描述" align="left" prop="lcDesc" />-->
      <el-table-column label="设备编号" align="center" prop="deviceNo" width="80"/>
      <el-table-column label="通道号" align="center" prop="channelNo" width="80"/>
      <el-table-column label="起始米标" align="center" prop="startMeter" width="80">
        <template slot-scope="scope">
          {{ scope.row.startMeter || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="结束米标" align="center" prop="endMeter" width="80">
        <template slot-scope="scope">
          {{ scope.row.endMeter || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="空间状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pj_location_state" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:location:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['project:location:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleEditMarker(scope.row)"
            v-hasPermi="['project:location:edit']"
            v-if="scope.row.deviceNo"
          >修改米标</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:location:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增修改米标对话框 -->
    <el-dialog title="修改米标" :visible.sync="markerOpen" width="500px" append-to-body>
      <el-form ref="markerForm" :model="markerForm" :rules="markerRules" label-width="100px">
        <el-form-item label="空间名称" prop="lcName">
          <el-input v-model="markerForm.lcName" :disabled="true" />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceNo">
          <el-input v-model="markerForm.deviceNo" :disabled="true" />
        </el-form-item>
        <el-form-item label="通道号" prop="channelNo">
          <el-input v-model="markerForm.channelNo" :disabled="true" />
        </el-form-item>
        <el-form-item label="起始米标" prop="startMeter">
          <el-input-number
            v-model="markerForm.startMeter"
            placeholder="请输入起始米标"
            :precision="0"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束米标" prop="endMeter">
          <el-input-number
            v-model="markerForm.endMeter"
            placeholder="请输入结束米标"
            :precision="0"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMarkerForm">确 定</el-button>
        <el-button @click="cancelMarker">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改空间管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="空间父亲id" prop="lcPid">
          <treeselect v-model="form.lcPid" :options="locationOptions" :normalizer="normalizer" placeholder="请选择空间父亲id" />
        </el-form-item>
        <el-form-item label="空间编码" prop="lcCode">
          <el-input v-model="form.lcCode" placeholder="请输入空间编码" />
        </el-form-item>
        <el-form-item label="空间名称" prop="lcName">
          <el-input v-model="form.lcName" placeholder="请输入空间名称" />
        </el-form-item>
        <el-form-item label="空间描述" prop="lcDesc">
          <el-input v-model="form.lcDesc" placeholder="请输入空间描述" />
        </el-form-item>
        <el-form-item label="空间状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.pj_location_state"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- Excel导入组件 -->
    <excel-import
      :visible="importVisible"
      :title="importTitle"
      :import-url="importUrl"
      :template-url="templateUrl"
      :template-file-name="templateFileName"
      :update-support="updateSupport"
      @update:visible="importVisible = $event"
      @download-template="handleDownloadTemplate"
      @upload-success="handleUploadSuccess"
      @upload-error="handleUploadError"
      @upload-progress="handleUploadProgress"
      @before-upload="handleBeforeUpload"
      @cancel="handleImportCancel"
    />
  </div>
</template>

<script>
import { listLocation, getLocation, delLocation, addLocation, updateLocation, updateLocationMarker  } from "@/api/project/location"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
// 导入Excel导入组件
import ExcelImport from "@/components/ExcelImport"
// 导入工具函数
import { downloadTemplate } from "@/utils/importUtils"

/**
 * 空间管理页面
 * 包含空间数据的增删改查、导入导出功能
 * 使用树形结构展示空间层级关系
 */
export default {
  name: "Location",
  dicts: ['pj_location_state'],
  components: {
    Treeselect,
    ExcelImport
  },
  data() {
    return {
      // 新增修改米标相关数据
      markerOpen: false,           // 修改米标对话框显示状态
      markerForm: {},              // 修改米标表单数据
      markerRules: {               // 修改米标表单验证规则
        startMeter: [
          { required: true, message: "起始米标不能为空", trigger: "blur" }
        ],
        endMeter: [
          { required: true, message: "结束米标不能为空", trigger: "blur" },
          { validator: this.validateMeterRange, trigger: "blur" }
        ]
      },
      // 导入相关参数
      importVisible: false,           // 导入对话框显示状态
      importTitle: "空间管理导入",     // 导入对话框标题
      importUrl: "/project/location/importData",        // 导入API地址
      templateUrl: "/project/location/importTemplate",  // 模板下载API地址
      templateFileName: "空间管理导入模板.xlsx",         // 模板文件名
      updateSupport: false,           // 是否支持更新已存在数据

      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 空间管理表格数据
      locationList: [],
      // 空间管理树选项
      locationOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        lcCode: null,
        lcName: null,
        status: null,
        deviceNo: null,
        channelNo: null,
        startMeter: undefined,  // 起始米标
        endMeter: undefined,    // 结束米标
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        lcPid: [
          { required: true, message: "空间父亲id不能为空", trigger: "change" }
        ],
        lcCode: [
          { required: true, message: "空间编码不能为空", trigger: "blur" }
        ],
        lcName: [
          { required: true, message: "空间名称不能为空", trigger: "blur" }
        ],
        lcDesc: [
          { required: true, message: "空间描述不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /**
     * 修改米标按钮操作
     * @param {Object} row 行数据
     */
    handleEditMarker(row) {
      this.resetMarkerForm()
      this.markerForm = {
        markerId: row.markerId,
        lcId: row.lcId,
        lcName: row.lcName,
        deviceNo: row.deviceNo,
        channelNo: row.channelNo,
        startMeter: row.startMeter,
        endMeter: row.endMeter
      }
      this.markerOpen = true
    },

    /**
     * 提交米标修改
     */
    submitMarkerForm() {
      this.$refs["markerForm"].validate(valid => {
        if (valid) {
          updateLocationMarker(this.markerForm).then(response => {
            this.$modal.msgSuccess("修改成功")
            this.markerOpen = false
            this.getList() // 刷新列表
          })
        }
      })
    },

    /**
     * 取消米标修改
     */
    cancelMarker() {
      this.markerOpen = false
      this.resetMarkerForm()
    },

    /**
     * 重置米标表单
     */
    resetMarkerForm() {
      this.markerForm = {
        markerId: null,
        lcId: null,
        lcName: null,
        deviceNo: null,
        channelNo: null,
        startMeter: null,
        endMeter: null
      }
      this.resetForm("markerForm")
    },

    /**
     * 验证米标范围
     * 结束米标必须大于起始米标
     */
    validateMeterRange(rule, value, callback) {
      if (value !== null && this.markerForm.startMeter !== null && value <= this.markerForm.startMeter) {
        callback(new Error("结束米标必须大于起始米标"))
      } else {
        callback()
      }
    },
    /**
     * 查询空间管理列表
     * 获取空间数据并转换为树形结构展示
     */
    getList() {
      this.loading = true
      listLocation(this.queryParams).then(response => {
        this.locationList = this.handleTree(response.data, "lcId", "lcPid")
        this.loading = false
      })
    },

    /**
     * 导入按钮操作
     * 打开导入对话框
     */
    handleImport() {
      this.importVisible = true
    },

    /**
     * 处理模板下载
     * @param {Object} params 下载参数
     */
    handleDownloadTemplate(params) {
      downloadTemplate(params.templateUrl, params.fileName)
        .then(() => {
          this.$modal.msgSuccess("模板下载成功")
        })
        .catch(error => {
          this.$modal.msgError("模板下载失败")
          console.error('下载模板失败:', error)
        })
    },

    /**
     * 处理上传成功
     * @param {Object} result 上传结果
     */
    handleUploadSuccess(result) {
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        result.message +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      )
      // 刷新列表
      this.getList()
    },

    /**
     * 处理上传失败
     * @param {Object} result 错误结果
     */
    handleUploadError(result) {
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        result.message +
        "</div>",
        "导入失败",
        { dangerouslyUseHTMLString: true }
      )
    },

    /**
     * 处理上传进度
     * @param {Object} progress 进度信息
     */
    handleUploadProgress(progress) {
      console.log('上传进度:', progress)
    },

    /**
     * 处理上传前验证
     * @param {File} file 上传文件
     */
    handleBeforeUpload(file) {
      console.log('上传文件:', file)
    },

    /**
     * 处理导入取消
     */
    handleImportCancel() {
      this.importVisible = false
    },

    /**
     * 转换空间管理数据结构
     * 用于Treeselect组件的格式适配
     * @param {Object} node 树节点
     * @return {Object} 格式化后的节点
     */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.lcId,
        label: node.lcName,
        children: node.children
      }
    },

    /**
     * 查询空间管理下拉树结构
     * 用于表单中的父空间选择
     */
    getTreeselect() {
      listLocation().then(response => {
        this.locationOptions = []
        const data = { lcId: 0, lcName: '顶级节点', children: [] }
        data.children = this.handleTree(response.data, "lcId", "lcPid")
        this.locationOptions.push(data)
      })
    },

    /**
     * 取消按钮操作
     * 关闭对话框并重置表单
     */
    cancel() {
      this.open = false
      this.reset()
    },

    /**
     * 表单重置
     * 清空表单数据
     */
    reset() {
      this.form = {
        lcId: null,
        lcPid: null,
        lcCode: null,
        lcName: null,
        lcDesc: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },

    /**
     * 搜索按钮操作
     * 执行查询并刷新列表
     */
    handleQuery() {
      this.getList()
    },

    /**
     * 重置按钮操作
     * 清空搜索条件并重新查询
     */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    /**
     * 新增按钮操作
     * @param {Object} row 行数据，用于设置父空间
     */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row != null && row.lcId) {
        this.form.lcPid = row.lcId
      } else {
        this.form.lcPid = 0
      }
      this.open = true
      this.title = "添加空间管理"
    },

    /**
     * 展开/折叠操作
     * 切换树形表格的展开状态
     */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },

    /**
     * 修改按钮操作
     * @param {Object} row 要修改的行数据
     */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      if (row != null) {
        this.form.lcPid = row.lcPid
      }
      getLocation(row.lcId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改空间管理"
      })
    },

    /**
     * 提交按钮
     * 表单验证并提交数据
     */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lcId != null) {
            updateLocation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addLocation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /**
     * 删除按钮操作
     * @param {Object} row 要删除的行数据
     */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除空间管理编号为"' + row.lcId + '"的数据项？').then(() => {
        return delLocation(row.lcId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
/* 可以添加一些自定义样式 */
.app-container {
  padding: 20px;
}
</style>
